//
//  SignUp.swift
//  HealthMonitoring
//
//  Created by YTYanK on 2018/6/7.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import RKDropdownAlert

class SignUp: HMViewController, UITextFieldDelegate{
    // MARK: - 变量
    // 密保答案
    var answerValue: String? //密保问题答案
    var answerId: String? //密保问题ID
    var oldPhone: String? //旧手机号码
    var oldCode: String?  //旧手机验证码
    var newPhone: String? //新手机号码
    var newCode: String? //新手机验证码
    var friendPhone: String? //亲友手机号码
    var friendCode: String? //亲友手机验证码
    /// 是否是更改绑定界面-从设置进来
    var isChangeUI: Bool = false
    
    // 遮罩view
    var _maskView: UIView?
    // MARK: - 常量
    let bgImg = UIImageView()
    let photoField = UITextField()
    let smsField = UITextField()
    let smsButton = UIButton()
    let referee = UITextField()
    
    let checkButton = UIButton()
    let clauseButton = UIButton()
    let nextStep = UIButton()
    
    
    
    // 线条
    let line = UIView()
    let line1 = UIView()
    let line2 = UIView()
    let lineVertical = UIView() //竖线
    /// 状态栏(statusbar)
    let statusRect = UIApplication.shared.statusBarFrame
    // MARK: - 周期
    override func viewDidLoad() {
        super.viewDidLoad()
    
        keyBordNotification(this: self, aShow: #selector(keyBoardWillShow(_:)), aHide: #selector(keyBoardWillHide(_:)))
    }
    
    deinit {
        //移除通知
        NotificationCenter.default.removeObserver(self)
    }
    
    // MARK: - 配置view
    override func setupView() {
        
        if(self._signStr == "注册") {
          self.title = "注册界面"
        }else {
           self.title = "手机验证"
        }
       
        
//        var zHodes = ["name":"珠海柑桔",
//                      "children": [
//                         "name":"斗门分局",
//                         "children":[
//                            ["name":"辑毒打电"],["name":"辑毒打电2"],["name":"辑毒打电3"]
//                         ]
//                      ]
//            ] as [String : Any]
//
//        print(zHodes["children"] as Any)
//        for (key, val ) in zHodes.enumerated() {
//            print(key, "----", val)
//            if val.key != "name" {
//                for (k, v) in zHodes["children"] as! [String : Any] {
//                    print(k, "++++----", v)
//                }
//            }
//
//        }
        
        
        
        
        view.backgroundColor = UIColor.white
        _maskView = UIView.createMaskView(this: self, action: #selector(onMark))
        
        view.addSubview(bgImg)
        view.addSubview(photoField)
        view.addSubview(line)
        view.addSubview(smsField)
        view.addSubview(lineVertical)
        view.addSubview(smsButton)
        view.addSubview(line1)
        view.addSubview(referee)
        view.addSubview(line2)
  
        view.addSubview(checkButton)
        view.addSubview(clauseButton)
        view.addSubview(nextStep)
        
        if(statusRect.height == 44.0) {
           bgImg.image = UIImage.init(named: "bgX.png")
        }else {
           bgImg.image = UIImage.init(named: "bg.png")
        }
        
        bgImg.centerXYAlign(view: view)
        bgImg.height(view: view)
        bgImg.width(view: view)
        
        photoField.topAlign(view: view, predicate: "30")
        photoField.leadingAlign(view: view, predicate: "60")
        photoField.trailingAlign(view: view, predicate: "-60")
        photoField.heightConstrain(predicate: "44")
        photoField.tag = 102
        photoField.placeholder = "手机号"
        photoField.delegate = self
        photoField.setValue(UIFont.systemFont(ofSize: 15), forKeyPath: "_placeholderLabel.font")
        photoField.setValue(UIColor.gray, forKeyPath: "_placeholderLabel.textColor")
//        photoField.keyboardType = UIKeyboardType.phonePad
        photoField.returnKeyType = UIReturnKeyType.route


        line.topVertically(view: photoField, predicate: "0")
        line.leadingAlign(view: view, predicate: "60")
        line.trailingAlign(view: view, predicate: "-60")
        line.backgroundColor = UIColor.gray
        line.heightConstrain(predicate: "2")


        smsField.topVertically(view: line, predicate: "10")
        smsField.leadingAlign(view: view, predicate: "60")
        smsField.trailingAlign(view: view, predicate: "-60")
        smsField.heightConstrain(predicate: "44")
        smsField.tag = 101
        smsField.placeholder = "验证码"
        smsField.delegate = self
        smsField.setValue(UIFont.systemFont(ofSize: 15), forKeyPath: "_placeholderLabel.font")
        smsField.setValue(UIColor.gray, forKeyPath: "_placeholderLabel.textColor")
        smsField.keyboardType = UIKeyboardType.numberPad
        smsField.returnKeyType = UIReturnKeyType.done

        smsButton.topVertically(view: line, predicate: "10")
        smsButton.trailingAlign(view: smsField, predicate: "0")
        smsButton.heightConstrain(predicate: "44")
        smsButton.widthConstrain(predicate: "100")
        smsButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        smsButton.addTarget(self, action: #selector(getCodeVerifying(sender:)), for: .touchUpInside)
        smsButton.setTitleColor(configure.shareConfigure.HMColor1, for: .normal)
        smsButton.setTitle("获取验证码", for: .normal)
   


        lineVertical.topVertically(view: line, predicate: "10")
        lineVertical.leadingAlign(view: smsButton, predicate: "0")
        lineVertical.heightConstrain(predicate: "42")
        lineVertical.backgroundColor = UIColor.gray
        lineVertical.widthConstrain(predicate: "2")


        line1.topVertically(view: smsField, predicate: "0")
        line1.leadingAlign(view: view, predicate: "60")
        line1.trailingAlign(view: view, predicate: "-60")
        line1.backgroundColor = UIColor.gray
        line1.heightConstrain(predicate: "2")

        if (self._signStr == "注册") {
        referee.topVertically(view: line1, predicate: "10")
        referee.leadingAlign(view: view,  predicate: "60")
        referee.trailingAlign(view: view, predicate: "-60")
        referee.heightConstrain(predicate: "44")
        referee.placeholder = "请输入推荐码"
            
            
        line2.topVertically(view: referee, predicate: "0")
        line2.leadingAlign(view: view, predicate: "60")
        line2.trailingAlign(view: view, predicate: "-60")
        line2.backgroundColor = UIColor.gray
        line2.heightConstrain(predicate: "2")
            
            
            
        checkButton.topVertically(view: line2, predicate: "20")
        checkButton.centerXAlign(view: view, predicate: "-50")
        checkButton.setImage(UIImage(named:"check_false.png"), for: .normal)
        checkButton.setTitleColor(UIColor.black, for: .normal)
        checkButton.setTitle(" 我同意 ", for: .normal)
        checkButton.setImage(UIImage(named:"check_true.png"), for: .selected)
        checkButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        checkButton.addTarget(self, action: #selector(checkClick(btn:)), for: .touchUpInside)
        checkButton.heightConstrain(predicate: "25")



        let mutStr: NSMutableAttributedString = NSMutableAttributedString(string: "《乐众康使用手册》")
        mutStr.addAttribute(NSAttributedStringKey.foregroundColor as NSAttributedStringKey , value: configure.shareConfigure.HMColor1, range: NSRange.init(location: 0, length: mutStr.length))
//        mutStr.addAttribute(NSAttributedStringKey.underlineStyle, value: 1, range: NSRange.init(location: 0, length:1))

        clauseButton.topVertically(view: line2, predicate: "20")
        clauseButton.leadingAlign(view: checkButton, predicate: "55")
        clauseButton.setTitleColor(UIColor.blue, for: .normal)
        clauseButton.setAttributedTitle(mutStr, for: .normal)
        clauseButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        clauseButton.addTarget(self, action: #selector(regulationsClick), for: .touchUpInside)
        clauseButton.heightConstrain(predicate: "25")
        }

        if isChangeUI == false {
         nextStep.topVertically(view: line2, predicate: "65")
        }else {
         nextStep.topVertically(view: line1, predicate: "65")
        }
        nextStep.leadingAlign(view: view, predicate: "60")
        nextStep.trailingAlign(view: view, predicate: "-60")
        nextStep.backgroundColor = UIColor.RGBA(r: 180, g: 180, b: 180, a: 1)
        nextStep.isEnabled = false
//        nextStep.isUserInteractionEnabled = false
        nextStep.heightConstrain(predicate: "44")
        if (self._signStr == "注册") {
          nextStep.setTitle("下一步", for: .normal)
        }else {
          nextStep.setTitle("绑定手机", for: .normal)
        }
        nextStep.setTitleColor(UIColor.white, for: .normal)
        nextStep.addTarget(self, action: #selector(nextStepClick), for: .touchUpInside)
        nextStep.layer.cornerRadius = 20
    }
    
    /**
     nextStepClick
     */
    @objc func nextStepClick(btn: UIButton) {

        if (self._signStr == "注册") {
           
            if (self.checkButton.isSelected == true){
                if (photoField.text != "" && smsField.text != ""){
                    let _str: String = photoField.text! as String

                    if (String.isTelNumber(num: _str) == true) {
                        
                       NetRequestTool.shareInstance.met = .get
                        let photoStr = self.photoField.text!
                        let smsStr = self.smsField.text!
                        NetRequestTool.request(url: "sms-code/verification", parameters: ["phone": photoStr,"code":smsStr, "role":"0"], success: { (json1) in
                            // 判断是否注册过
                            if json1["data"]["registered"] != true {
                                NetRequestTool.request(url: "security-config", parameters: [:], success: { (json) in
                                    let bindingChange  = BindingChange()
                                    bindingChange._signStr =  "设置密保"
                                    bindingChange.signUpPhone = photoStr
                                    bindingChange.pickerAry = json["data"].arrayObject
                                    self.pushViewController(bindingChange)
                                }, fail: { (err, msg) in
                                    
                                    RKDropdownAlert.title("温馨提醒!", message: "该账号已注册过，请更换号码注册。")
                                    //   RKDropdownAlert.title("请注意～", message:msg, backgroundColor: UIColor.green, textColor: UIColor.red, time: 5)
                                }, complete: {
                                    
                                })
                            }else {
//                              print("---registered = false")
                                RKDropdownAlert.title("温馨提醒!", message: "该账号已注册过，请更换号码注册。")
                            }
                            
                          
 
                        }, fail: { (error, msg) in
                            print("------------ \(error)")
                            RKDropdownAlert.title("请注意～", message:msg, backgroundColor: UIColor.green, textColor: UIColor.red, time: 5)
                        }) {
                            //
                        }
                        

                    }else {
                         print("1---->>")
                    }

                }else {
                    print("2---->>请输入完整信息")
                }
                
            }else {
                //提示下
            }

        }else {
            
            if (self.smsField.text?.count)! > 0 {
                self.newCode = self.smsField.text
                
                if isChangeUI == true {
                    
                    NetRequestTool.shareInstance.met = .post
                
                    NetRequestTool.request(url: "sms-code/rebind/verification", parameters: ["oldPhone": self.oldPhone!, "oldCode": self.oldCode!, "newPhone": self.newPhone!, "newCode": self.newCode!], success: { (json) in
                        
                            print("---->", json)
                    }, fail: { (error, msg) in
                           print("------>", msg)
                    }) { }
                }else {
                    //通过密保重绑
                    NetRequestTool.request(url: "rebind/security-question/verification", parameters: ["sqId": self.answerId!,"sqAnswer": self.answerValue!,"oldPhone": self.oldPhone!,"newPhone": self.newPhone!,"newCode": self.newCode!], success: { (json) in
                        //改绑成功直接登录
                        self.navigationController?.popToRootViewController(animated: true)
                    }, fail: { (err, msg) in
                        RKDropdownAlert.title("温馨提醒!", message: msg)
                    }) {}
                }
            }
            
        }
    }
    /**
     checkClick
     */
    @objc func checkClick(btn: UIButton) {
        btn.isSelected = !btn.isSelected
        //判断是否开启按钮
       self.setButtonSytle()
    }
    /**
     获取验证码
     */
    @objc func getCodeVerifying(sender: UIButton){
        
        let _str: String = photoField.text! as String
        
        if (String.isTelNumber(num: _str) == true) {
            
            sender.countdownButton(second: 60, title: "获取验证码")
            if self._signStr == "注册" {
                 // 注册手机发验证码
                NetRequestTool.shareInstance.met = .get
                NetRequestTool.request(url: "sms-code/send", parameters: ["phone": _str], success: { (json) in
                    self.showToast(message: json["msg"].stringValue)
                }, fail: { (error, msg) in
                    RKDropdownAlert.title("温馨提醒!", message: msg)
                }) {}
                
            }else {
                NetRequestTool.shareInstance.met = .get
                // 新手机发验证码
                NetRequestTool.request(url: "sms-code/rebind-new/send", parameters: ["phone": _str], success: { (json) in
                    self.newPhone = _str
                    self.showToast(message: json["msg"].stringValue)
                }, fail: { (error, msg) in
                    RKDropdownAlert.title("温馨提醒!", message: msg)
                }) {}
            }
            
        }else {
            RKDropdownAlert.title("请注意～", message:"手机格式错误，请重新输入", backgroundColor: UIColor.green, textColor: UIColor.red, time: 5)
        }

    }
    
    /**
      Regulations
      */
    @objc func regulationsClick(){
        print("Regulations")
    }
    
    // UITapGestureRecognizer
    @objc func onMark(send: UITapGestureRecognizer) {
       _maskView?.removeFromSuperview()
       self.smsField.resignFirstResponder()//结束编辑状态
       self.photoField.resignFirstResponder()//结束编辑状态
    }
    // 设置按钮表现效果
    func setButtonSytle()  {
        //判断是否开启按钮
        if self._signStr == "注册" {
            if (self.checkButton.isSelected == true && self.smsField.text!.count > 0 && self.photoField.text!.count > 0) {
                openButtonRecognition(setStyleBtn: self.nextStep, isOpen: true)
            }else {
                openButtonRecognition(setStyleBtn: self.nextStep, isOpen: false)
            }
        }else {
            if ( self.smsField.text!.count > 0 && self.photoField.text!.count > 0) {
                openButtonRecognition(setStyleBtn: self.nextStep, isOpen: true)
            }else {
                openButtonRecognition(setStyleBtn: self.nextStep, isOpen: false)
            }
        }
        
        

    }
    
    /**
     键盘监控
     */
    @objc func keyBoardWillShow(_ notification: Notification){
        self.view.window?.addSubview(_maskView!)
//        print("------->>keyBoardWillShow")
    }
    
    @objc func keyBoardWillHide(_ notification: Notification){
//         print("------->>keyBoardWillHide")
         self.setButtonSytle()
    }
    
    
    // MARK: - textField Delegate
    func textFieldDidBeginEditing(_ textField: UITextField) {
        print("didBegin")
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        print("didEnd")
    }
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        print("1 textFieldShouldBeginEditing")
        return true
    }
    
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        print("2 textFieldDidBeginEditing")
        return true
    }
    
    // 点键盘按钮
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField.tag == 102 {
            self.smsField.becomeFirstResponder()
        }else {
        
        }
        return true
    }

    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let text = textField.text!
        let len = text.count + string.count - range.length
        if textField.tag == 101 {
            return (len <= 6)
        }else {
            return (len <= 11)
        }
        
    }
}
